﻿from PySide6.QtCore import QDateTime, Slot
from PySide6.QtWidgets import QMessageBox
from PySide6.QtGui import QIcon
from Devices.DeviceWindow import DeviceWindow
from Devices.Chiot.MatterBulb.DeviceMatterBulb import DeviceMatterBulb
from Devices.Chiot.MatterBulb.MatterBulbParser import MatterBulbParser

from Devices.Chiot.MatterBulb.Forms.MatterBulbWindow_UI import Ui_FormMatterBulbWindow

class MatterBulbWindow(DeviceWindow):
    def __init__(self, supportDevice, parent = None):
        super().__init__(supportDevice, parent)

        self.__ui = Ui_FormMatterBulbWindow()
        self.__ui.setupUi(self)
        self.SetupUi(self.__ui)
        
        self.__DeviceFullStatus = DeviceMatterBulb.DeviceFullStatus()

        self._HttpServerWindow.SetLogServerEnable(False)
        self._OtaUrl = self.__ui.lineEdit_downloadUrl.text()

        self.__ui.tabWidget.setCurrentIndex(0)
        self.__ui.progressBar_Ota.setVisible(False)

    def Connect(self, cmdPort, logPort):
        super().Connect(cmdPort, logPort)
        self.__ui.lineEdit_downloadUrl.setText(self._OtaUrl % (self._HttpServerWindow.GetIP(), self._HttpServerWindow.GetPort(), self._SupportDevice.deviceBinName))

    def Connected(self, ip, port):
        cmd = MatterBulbParser.PackGetFullStatus()
        self.SendCommandText(cmd)

    def SetLightAttrUI(self, fullStatus):
        #禁用信号，避免重复发送
        self.__ui.horizontalSlider_rgbBrightness.blockSignals(True)
        self.__ui.horizontalSlider_Saturation.blockSignals(True)
        self.__ui.horizontalSlider_Red.blockSignals(True)
        self.__ui.horizontalSlider_Green.blockSignals(True)
        self.__ui.horizontalSlider_Blue.blockSignals(True)
        self.__ui.horizontalSlider_whiteBrightness.blockSignals(True)
        self.__ui.horizontalSlider_Temprature.blockSignals(True)

        #灯光设置
        self.__ui.horizontalSlider_rgbBrightness.setValue(fullStatus.lightAttr.rgb.rgbBrightness)
        self.__ui.horizontalSlider_Saturation.setValue(fullStatus.lightAttr.rgb.saturation)
        self.__ui.horizontalSlider_Red.setValue(fullStatus.lightAttr.rgb.red)
        self.__ui.horizontalSlider_Green.setValue(fullStatus.lightAttr.rgb.green)
        self.__ui.horizontalSlider_Blue.setValue(fullStatus.lightAttr.rgb.blue)
        self.__ui.horizontalSlider_whiteBrightness.setValue(fullStatus.lightAttr.white.whiteBrightness)
        self.__ui.horizontalSlider_Temprature.setValue(fullStatus.lightAttr.white.temprature)

        self.__ui.label_rgbBrightness.setText(str(fullStatus.lightAttr.rgb.rgbBrightness))
        self.__ui.label_Saturation.setText(str(fullStatus.lightAttr.rgb.saturation))
        self.__ui.label_Red.setText(str(fullStatus.lightAttr.rgb.red))
        self.__ui.label_Green.setText(str(fullStatus.lightAttr.rgb.green))
        self.__ui.label_Blue.setText(str(fullStatus.lightAttr.rgb.blue))
        self.__ui.label_whiteBrightness.setText(str(fullStatus.lightAttr.white.whiteBrightness))
        self.__ui.label_Temprature.setText(str(fullStatus.lightAttr.white.temprature))

        #启用信号
        self.__ui.horizontalSlider_rgbBrightness.blockSignals(False)
        self.__ui.horizontalSlider_Saturation.blockSignals(False)
        self.__ui.horizontalSlider_Red.blockSignals(False)
        self.__ui.horizontalSlider_Green.blockSignals(False)
        self.__ui.horizontalSlider_Blue.blockSignals(False)
        self.__ui.horizontalSlider_whiteBrightness.blockSignals(False)
        self.__ui.horizontalSlider_Temprature.blockSignals(False)

    def SetDeviceFullStatus(self, msgValue):
        if MatterBulbParser.ParseFullStatus(msgValue, self.__DeviceFullStatus):
            #基本信息
            self.__ui.label_Mac.setText(self.__DeviceFullStatus.mac)
            self.__ui.label_firmwareVersion.setText(self.__DeviceFullStatus.firmwareVersion)
            self.__ui.label_hardwareVersion.setText(self.__DeviceFullStatus.hardwareVersion)
            self.__ui.label_protocol.setText(self.__DeviceFullStatus.protocol)
            self.SetPowerType(self.__DeviceFullStatus.powerType)
            self.SetLedDriver(self.__DeviceFullStatus.ledDriver)
            self.SetInterfaceType(self.__DeviceFullStatus.interfaceType)

            self.__ui.label_buildTime.setText(self.__DeviceFullStatus.buildTime)

            #模式设置
            self.__ui.checkBox_switch.setChecked(self.__DeviceFullStatus.switch_state)
            self.__ui.checkBox_noDisturb.setChecked(self.__DeviceFullStatus.noDisturb)

            if self.__DeviceFullStatus.lightAttr.lightMode == DeviceMatterBulb.LightMode.LIGHT_RGB:
                self.__ui.label_CurrLightMode.setText("彩光")
                self.__ui.label_CurrLightMode.setStyleSheet("font:12pt; color:rgb(255, 0, 255);")
                self.__ui.groupBox_RGB.setEnabled(True)
                self.__ui.groupBox_White.setEnabled(False)
            elif self.__DeviceFullStatus.lightAttr.lightMode == DeviceMatterBulb.LightMode.LIGHT_WHITE:
                self.__ui.label_CurrLightMode.setText("白光")
                self.__ui.label_CurrLightMode.setStyleSheet("font:12pt; color:black;")
                self.__ui.groupBox_RGB.setEnabled(False)
                self.__ui.groupBox_White.setEnabled(True)
            else:
                self.__ui.label_CurrLightMode.setText("氛围")
                self.__ui.label_CurrLightMode.setStyleSheet("font:12pt; color:rgb(170, 0, 255);")
                self.__ui.groupBox_RGB.setEnabled(False)
                self.__ui.groupBox_White.setEnabled(False)

            #灯光设置
            self.SetLightAttrUI(self.__DeviceFullStatus)

            #电流设置
            self.__ui.lineEdit_Current_Blue.setText(str(self.__DeviceFullStatus.currents.blue))
            self.__ui.lineEdit_Current_Red.setText(str(self.__DeviceFullStatus.currents.red))
            self.__ui.lineEdit_Current_Green.setText(str(self.__DeviceFullStatus.currents.green))
            self.__ui.lineEdit_Current_Warm.setText(str(self.__DeviceFullStatus.currents.warm))
            self.__ui.lineEdit_Current_Cold.setText(str(self.__DeviceFullStatus.currents.cold))

    def SetPowerType(self, powerType, messageBox = False):
        powerTypeStr = "未知"
        if powerType == DeviceMatterBulb.PowerType.BULB_TYPE_9W:
            powerTypeStr = "9W"
            self.__ui.label_powerType.setStyleSheet("font:12pt; color:Blue;")
        elif powerType == DeviceMatterBulb.PowerType.BULB_TYPE_12W:
            powerTypeStr = "12W"
            self.__ui.label_powerType.setStyleSheet("font:12pt; color:rgb(170, 0, 255);")
        else:
            self.__ui.label_powerType.setStyleSheet("font:12pt; color:Red;")

        self.__ui.label_powerType.setText(powerTypeStr)
        self.__ui.comboBox_powerType.setCurrentText(powerTypeStr)

        if messageBox:
            self.ShowMessageBox("设置设备类型", "设备类型已设置为%s!" % (powerTypeStr))

    def SetLedDriver(self, ledDriver, messageBox = False):
        ledDriverStr = "未知"
        if ledDriver == DeviceMatterBulb.LedDriver.LED_DRIVER_BP5758D:
            ledDriverStr = "BP5758D"
            self.__ui.label_ledDriver.setStyleSheet("font:12pt; color:Blue;")
        elif ledDriver == DeviceMatterBulb.LedDriver.LED_DRIVER_BP1658CJ:
            ledDriverStr = "BP1658CJ"
            self.__ui.label_ledDriver.setStyleSheet("font:12pt; color:rgb(170, 0, 255);")
        else:
            self.__ui.label_ledDriver.setStyleSheet("font:12pt; color:Red;")

        self.__ui.label_ledDriver.setText(ledDriverStr)
        self.__ui.comboBox_ledDriver.setCurrentText(ledDriverStr)

        if messageBox:
            self.ShowMessageBox("设置驱动芯片", "设备驱动芯片已设置为%s!" % (ledDriverStr))

    def SetInterfaceType(self, interfaceType, messageBox = False):
        interfaceTypeStr = "未知"
        if interfaceType == DeviceMatterBulb.InterfaceType.INTERFACE_TYPE_E27:
            interfaceTypeStr = "E27"
            self.__ui.label_InterfaceType.setStyleSheet("font:12pt; color:Blue;")
        elif interfaceType == DeviceMatterBulb.InterfaceType.INTERFACE_TYPE_B22:
            interfaceTypeStr = "B22"
            self.__ui.label_InterfaceType.setStyleSheet("font:12pt; color:rgb(170, 0, 255);")
        else:
            self.__ui.label_InterfaceType.setStyleSheet("font:12pt; color:Red;")

        self.__ui.label_InterfaceType.setText(interfaceTypeStr)
        self.__ui.comboBox_InterfaceType.setCurrentText(interfaceTypeStr)

        if messageBox:
            self.ShowMessageBox("设置电源接口", "电源接口已设置为%s!" % (interfaceTypeStr))

    def CmdDateReceived(self, data):
        ret, msgName, msgValue = MatterBulbParser.ParseMsg(data)
        if not ret:
            return

        if msgName == "getFullStatus":
            self.SetDeviceFullStatus(msgValue)
            self.ShowMessageBox("设备信息同步", "信息同步成功!")
        elif msgName == "heartbeat":
            self.SetDeviceFullStatus(msgValue)
            self.ShowMessageBox("设备信息同步", "信息同步成功!")
        elif msgName == "rptStatus":
            self.SetDeviceFullStatus(msgValue)
        elif msgName == "setPowerType":
            powerType = msgValue["powerType"]
            self.__DeviceFullStatus.powerType = powerType
            self.SetPowerType(powerType, True)
        elif msgName == "setLedDriver":
            ledDriver = msgValue["ledDriver"]
            self.__DeviceFullStatus.ledDriver = ledDriver
            self.SetLedDriver(ledDriver, True)
        elif msgName == "setInterfaceType":
            interfaceType = msgValue["interfaceType"]
            self.__DeviceFullStatus.interfaceType = interfaceType
            self.SetInterfaceType(interfaceType, True)
        elif msgName == "setWiFi":
            ret = msgValue["ret"]
            self.ShowMessageBox("设置Wi-Fi", "Wi-Fi信息设置%s!" % ("成功" if ret != 0 else "失败"), QMessageBox.Information if ret != 0 else QMessageBox.Critical)
        elif msgName == "setCurrent":
            self.SetDeviceFullStatus(msgValue)
            self.ShowMessageBox("设置电流", "设置电流完成!")
        elif msgName == "otaProcess":
            if self._OtaStarted:
                otaProcess = DeviceMatterBulb.OtaProcess()
                MatterBulbParser.ParseOtaProcess(msgValue, otaProcess)
                if len(otaProcess.startTime) > 0 and len(otaProcess.totalTime) > 0:
                    startTime = otaProcess.startTime.toLongLong()
                    startDateTime = QDateTime.fromMSecsSinceEpoch(startTime).toString("yyyy-MM-dd HH:mm:ss")
                    self._OtaStarted = False
                    self.ShowMessageBox("设备升级", "设备升级开始\r\n开始时间\"%s\",预计用时%2秒!" % (startDateTime, otaProcess.totalTime))
                else:
                    if otaProcess.progress.isdigit():
                        progress = int(otaProcess.progress)
                        self.__ui.progressBar_Ota.setVisible(100 != progress)
                        self.__ui.progressBar_Ota.setValue(progress)

                    if otaProcess.process.isdigit():
                        process = int(otaProcess.process)
                        if 1 == process:
                            self._OtaStarted = False
                            self.ShowMessageBox("设备升级", "设备下载完成,等待安装...")

    @Slot()
    def on_checkBox_switch_clicked(self):
        cmd = MatterBulbParser.PackSetSwitch(self.__ui.checkBox_switch.isChecked())
        self.SendCommandText(cmd)
        
    @Slot()
    def on_checkBox_noDisturb_clicked(self):
        cmd = MatterBulbParser.PackSetNoDisturb(self.__ui.checkBox_noDisturb.isChecked())
        self.SendCommandText(cmd)
        
    @Slot()
    def on_pushButton_Sync_clicked(self):
        cmd = MatterBulbParser.PackGetFullStatus()
        self.SendCommandText(cmd)
        
    @Slot(int)
    def on_horizontalSlider_rgbBrightness_valueChanged(self, value):
        cmd = MatterBulbParser.PackSetLight("rgbBrightness", "brightness", value)
        self.SendCommandText(cmd)
                
    @Slot(int)
    def on_horizontalSlider_Saturation_valueChanged(self, value):
        cmd = MatterBulbParser.PackSetLight("saturation", "ratio", value)
        self.SendCommandText(cmd)
                
    @Slot(int)
    def on_horizontalSlider_Red_valueChanged(self, value):
        cmd = MatterBulbParser.PackSetLight("colour", "red", value)
        self.SendCommandText(cmd)
                
    @Slot(int)
    def on_horizontalSlider_Green_valueChanged(self, value):
        cmd = MatterBulbParser.PackSetLight("colour", "green", value)
        self.SendCommandText(cmd)
                
    @Slot(int)
    def on_horizontalSlider_Blue_valueChanged(self, value):
        cmd = MatterBulbParser.PackSetLight("colour", "blue", value)
        self.SendCommandText(cmd)
                
    @Slot(int)
    def on_horizontalSlider_whiteBrightness_valueChanged(self, value):
        cmd = MatterBulbParser.PackSetLight("whiteBrightness", "brightness", value)
        self.SendCommandText(cmd)
                
    @Slot(int)
    def on_horizontalSlider_Temprature_valueChanged(self, value):
        cmd = MatterBulbParser.PackSetLight("colorTemperature", "ratio", value)
        self.SendCommandText(cmd)
                
    @Slot()
    def on_pushButton_SetRGB_clicked(self):
        rgb = DeviceMatterBulb.RGB(int(self.__ui.horizontalSlider_rgbBrightness.value()), self.__ui.horizontalSlider_Saturation.value(), int(self.__ui.horizontalSlider_Red.value()), int(self.__ui.horizontalSlider_Green.value()), int(self.__ui.horizontalSlider_Blue.value()))
        cmd = MatterBulbParser.PackSetRGB(rgb)
        self.SendCommandText(cmd)

        self.__ui.label_CurrLightMode.setText(("彩光"))
        self.__ui.label_CurrLightMode.setStyleSheet("font:12pt; color:rgb(255, 0, 255);")
                        
    @Slot()
    def on_pushButton_SetWhite_clicked(self):
        white = DeviceMatterBulb.White(int(self.__ui.horizontalSlider_whiteBrightness.value()), int(self.__ui.horizontalSlider_Temprature.value()))
        cmd = MatterBulbParser.PackSetWhite(white)
        self.SendCommandText(cmd)

        self.__ui.label_CurrLightMode.setText(("白光"))
        self.__ui.label_CurrLightMode.setStyleSheet("font:12pt; color:black;")
                                    
    @Slot()
    def on_pushButton_unbind_clicked(self):
        cmd = MatterBulbParser.PackUnbind()
        self.SendCommandText(cmd)

    @Slot(int)
    def on_comboBox_powerType_activated(self, index):
        cmd = MatterBulbParser.PackSetPowerType(index)
        self.SendCommandText(cmd)
                                    
    @Slot(int)
    def on_comboBox_ledDriver_activated(self, index):
        cmd = MatterBulbParser.PackSetLedDriver(index)
        self.SendCommandText(cmd)

    @Slot(int)
    def on_comboBox_InterfaceType_activated(self, index):
        cmd = MatterBulbParser.PackSetInterfaceType(index)
        self.SendCommandText(cmd)
                                    
    @Slot()
    def on_pushButton_SendWiFi_clicked(self):
        cmd = MatterBulbParser.PackSetWiFi(self.__ui.lineEdit_SSID.text(), self.__ui.lineEdit_Password.text())
        self.SendCommandText(cmd)
                                    
    @Slot()
    def on_pushButton_upgrade_clicked(self):
        cmd = MatterBulbParser.PackUpgrade(self.__ui.lineEdit_upgradePackageId.text(), self.__ui.lineEdit_downloadUrl.text(), self.__ui.label_Mac.text(), self.__ui.lineEdit_newVersion.text(), self.__ui.lineEdit_md5.text(), self.__ui.lineEdit_size.text())
        self.SendCommandText(cmd)
        self._OtaStarted = True
                                    
    @Slot()
    def on_pushButton_SetCurrent_clicked(self):
        cmd = MatterBulbParser.PackSetCurrent(int(self.__ui.lineEdit_Current_Red.text()), int(self.__ui.lineEdit_Current_Green.text()), int(self.__ui.lineEdit_Current_Blue.text()), int(self.__ui.lineEdit_Current_Warm.text()), int(self.__ui.lineEdit_Current_Cold.text()))
        self.SendCommandText(cmd)

    def HttpStarted(self):
        self.__ui.lineEdit_downloadUrl.setText(self._OtaUrl % (self._HttpServerWindow.GetIP(), self._HttpServerWindow.GetPort(), self._SupportDevice.deviceBinName))

    def HttpStopped(self):
        pass

